//
//  LQResetPasswordViewController.m
//  LQProductIntelligenceService
//
//  Created by Yim on 16/6/30.
//  Copyright © 2016年 张宁. All rights reserved.
//

#import "LQResetPasswordViewController.h"
#import "HZQRegexTestter.h"
#import "AFNetworking.h"
#import "LQLoginViewController.h"

@interface LQResetPasswordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *resetPasswordView;

@property (weak, nonatomic) IBOutlet UIButton *resetPasswordBtn;

@property (weak, nonatomic) IBOutlet UIView *baseView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *baseViewTopConstraint;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *repeatPasswordTextField;
@property (weak, nonatomic) IBOutlet UITextField *verifyCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *timeButton;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIView *remindView;
@property (weak, nonatomic) IBOutlet UILabel *remindLabel;

- (IBAction)clickGetVerifySurplusTimeBtn:(UIButton *)sender;
- (IBAction)clickResetPasswordBtn:(UIButton *)sender;

@property (nonatomic, strong) NSTimer* timer2;

@property (nonatomic, strong) NSTimer* timer1;

@property(nonatomic)CGFloat initialTopConstant;

@end

static int count = 0;

@implementation LQResetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createBtn];
    
    self.timeLabel.hidden = YES;
    
    [_timer2 invalidate];
    [_timer1 invalidate];
    count = 0;
    
    self.initialTopConstant = self.baseViewTopConstraint.constant;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 给Filed设置左边视图
    [self settingsFieldLeftView];
}

- (void) settingsFieldLeftView
{
    
    UIImage *imageP = [UIImage imageNamed:@"phone"];
    UIImageView *leftVP = [[UIImageView alloc]initWithImage:imageP];
    leftVP.contentMode = UIViewContentModeCenter;
    leftVP.frame = CGRectMake(0, 0, 50, 20);
    self.phoneTextField.leftViewMode = UITextFieldViewModeAlways;
    self.phoneTextField.leftView = leftVP;
    
    UIImage *imageL = [UIImage imageNamed:@"lock"];
    UIImageView *leftVL = [[UIImageView alloc]initWithImage:imageL];
    leftVL.contentMode = UIViewContentModeCenter;
    leftVL.frame = CGRectMake(0, 0, 50, 20);
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.passwordTextField.leftView = leftVL;
    
    UIImage *imageRL = [UIImage imageNamed:@"lock"];
    UIImageView *leftVRL = [[UIImageView alloc]initWithImage:imageRL];
    leftVRL.contentMode = UIViewContentModeCenter;
    leftVRL.frame = CGRectMake(0, 0, 50, 20);
    self.repeatPasswordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.repeatPasswordTextField.leftView = leftVRL;

    UIImage *imageV = [UIImage imageNamed:@"verifycode"];
    UIImageView *leftVV = [[UIImageView alloc]initWithImage:imageV];
    leftVV.contentMode = UIViewContentModeCenter;
    leftVV.frame = CGRectMake(0, 0, 50, 20);
    self.verifyCodeTextField.leftViewMode = UITextFieldViewModeAlways;
    self.verifyCodeTextField.leftView = leftVV;
}

- (void) createBtn
{
     UIButton *button = [UIButton buttonWithBackAddTarget:self addAction:@selector(backVC)];
    [self.view addSubview:button];
    
}
- (void) backVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.phoneTextField) {
        
        [self.passwordTextField becomeFirstResponder];
        
    }else if (textField == self.passwordTextField)
    {
        [self.repeatPasswordTextField becomeFirstResponder];
    }else if (textField == self.repeatPasswordTextField)
    {
        [self.verifyCodeTextField becomeFirstResponder];
    }else if (textField == self.verifyCodeTextField)
    {
        [self.view endEditing:YES];
        [self clickResetPasswordBtn:nil];
    }
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)clickGetVerifySurplusTimeBtn:(UIButton *)sender
{
    BOOL isSuccess;
    isSuccess = [HZQRegexTestter validatePhone:self.phoneTextField.text];
    
    if (isSuccess) {
        self.timeLabel.text = @"剩余60秒";
        [_timer2 invalidate];
        [_timer1 invalidate];
        
        count = 0;
        
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES];
        NSTimer *timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
        _timer1 = timer;
        _timer2 = timer2;
        
        self.timeLabel.hidden = NO;
        self.timeButton.hidden = YES;
    }else
    {
//        [MBProgressHUD showError:@"请输入正确的手机号!"];
        UIAlertController *alert = [UIAlertController alertWithTitle:@"提示" alertStyle:UIAlertControllerStyleAlert contentString:@"请输入手机号" andWithCancel:@"确定"];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

}
- (void) showRepeatButton
{
    self.timeLabel.hidden = YES;
    self.timeButton.hidden = NO;
    [self.timeButton setTitle:@"重新获取" forState:UIControlStateNormal];
    [_timer1 invalidate];
    return;
}

- (void) updateTime
{
    count++;
    if (count >= 60) {
        [_timer2 invalidate];
        return;
    }
    self.timeLabel.text = [NSString stringWithFormat:@"剩余%i秒",60 - count];
}

- (IBAction)clickResetPasswordBtn:(UIButton *)sender
{
    self.resetPasswordBtn.selected = !self.resetPasswordBtn.selected;
    [self judgePhoneInputIsTrue];
}

- (void) judgePhoneInputIsTrue
{
    BOOL phoneIsSuccess;
    phoneIsSuccess = [HZQRegexTestter validatePhone:self.phoneTextField.text];
    
    if (!phoneIsSuccess)
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确的手机号" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
        return;
    }else
    {
        [self verifyPhoneIsRegister];
        return;
    }
    
}

- (void) judgePasswordAndVerifyCodeIsTrue
{
    BOOL passwordIsSuccess;
    passwordIsSuccess = [HZQRegexTestter validateStrWithRange:@"{6,20}" str:self.passwordTextField.text];
    
    BOOL repeatPasswordIsSuccess;
    repeatPasswordIsSuccess = [HZQRegexTestter validateStrWithRange:@"{6,20}" str:self.repeatPasswordTextField.text];
    
    if (!passwordIsSuccess)
    {
        self.remindLabel.text = @"密码不能为空长度不能低于6位";
        [self remindAnimationResult];
        [self.passwordTextField becomeFirstResponder];
        return;
    }else if (!repeatPasswordIsSuccess)
    {
        self.remindLabel.text = @"密码不能为空长度不能低于6位";
        [self remindAnimationResult];
        [self.repeatPasswordTextField becomeFirstResponder];
        return;
    }else if (![self.passwordTextField.text isEqualToString:self.repeatPasswordTextField.text])
    {
        UIAlertController *alert = [UIAlertController alertWithTitle:@"提示" alertStyle:UIAlertControllerStyleAlert contentString:@"密码输入不一致" andWithCancel:@"确定"];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }else if (self.verifyCodeTextField.text.length != 6)
    {
        self.remindLabel.text = @"验证码输入错误!";
        [self remindAnimationResult];
        [self.verifyCodeTextField becomeFirstResponder];
        return;
    }else
    {
      
    }
}

- (void) resetPassword
{
   
    
}

- (void) verifyPhoneIsRegister
{
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"phone"] = self.phoneTextField.text;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:@"" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        BOOL isRegister = [string boolValue];
        
        if (isRegister) {
            [self judgePasswordAndVerifyCodeIsTrue];
        }else
        {
            UIAlertController *alert = [UIAlertController alertWithTitle:@"提示" alertStyle:UIAlertControllerStyleAlert contentString:@"手机号未注册,请联系西筑客服!" andWithCancel:@"确定"];
            [self presentViewController:alert animated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        MYLog(@"%@",error);
//        [MBProgressHUD showError:@"连接服务器失败!"];
    }];
    
}


- (void) remindAnimationResult
{
    self.remindView.hidden = NO;
    CGFloat distance =  70;
    self.baseViewTopConstraint.constant = distance;
    
    [UIView animateWithDuration:0.1 animations:^{
        [self.view layoutIfNeeded];
    }];
    if (self.resetPasswordBtn.selected) {
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.0 initialSpringVelocity:5.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGPoint point = self.resetPasswordView.center;
            point.x += 3;
            [self.resetPasswordView setCenter:point];
        } completion:nil];
        [self recoverRemindView];
    }else
    {
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.0 initialSpringVelocity:5.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGPoint point = self.resetPasswordView.center;
            point.x -= 3;
            [self.resetPasswordView setCenter:point];
        } completion:nil];
        [self recoverRemindView];
    }
}

/**
 *  收回View
 */
- (void) recoverRemindView
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.remindView.hidden = YES;
                CGFloat distance =  self.initialTopConstant;
                self.baseViewTopConstraint.constant = distance;
                [UIView animateWithDuration:0.1 animations:^{
                    [self.view layoutIfNeeded];
                }];
            });
        });
    });
}

- (void)dealloc
{
    [_timer1 invalidate];
    [_timer2 invalidate];
    _timer1 = nil;
    _timer2 = nil;
}


@end
